<?php
declare (strict_types = 1);
namespace app\common\self;

use think\cache\driver\Redis as tpRedis;

class SelfRedis extends tpRedis{
    public $redis;
    public $config = [];
    /**
     * SelfRedis constructor.
     * @param string $config_cache 实例化对象的配置,默认为redis
     */
    public function __construct($config_cache = 'redis')
    {
        $this->redis = Redis::createRedis($config_cache);
        $this->config =  Redis::getConfig();
    }

    /**
     * 切换缓存配置
     */
    public function switch($config_cache = 'redis')
    {
        $this->redis = Redis::createRedis($config_cache);
        $this->config =  Redis::getConfig();
        return $this->redis;
    }
}

/**
 * Class Redis 单例设计模式 只需要调用静态方法createRedis
 * @package app\common\self
 */
Class Redis
{
    // 缓存的实例化
    private static $redis;
    // 缓存的配置_字符串
    private static $config_cache = '';
    // 缓存的配置信息
    private static $config_arr = [];

    private function __construct()
    {
    }

    // 创建redis实例化
    public static function createRedis($config_cache = 'redis'){
        if($config_cache != 'redis' && env('develop'))
            $config_cache = 'redis';
        // 不等于 说明是新的 或者首创建
        if(self::$config_cache != $config_cache){
            // 存储
            self::$config_arr = config('cache.stores.'.$config_cache,[]);
            self::$config_cache = $config_cache;
            self::$redis = self::$redis = new tpRedis(self::$config_arr);
            return self::$redis;
        }else{
            // 判断是否为实例化
            if(!self::$redis && !(self::$redis instanceof tpRedis)){
                self::$config_arr = config('cache.stores.'.$config_cache,[]);
                self::$redis = self::$redis = new tpRedis(self::$config_arr);
            }
            return self::$redis;
        }
    }


    // 获取当前的配置库
    public static function getConfig(){
        return self::$config_arr;
    }
}